//
//  CXHTradPlusSplashAdapter.m
//  CXHAdSDK-TradPlus
//
//  Created by 陈坤 on 2023/9/20.
//

#import "CXHTradPlusSplashAdapter.h"
#import <TradPlusAds/TradPlusAdWaterfallItem.h>
#import <CXHAdSDK-Core/CXHAdSDKSplashAd.h>
#import <CXHAdSDK-Kit/CXHUtilsKit.h>
#import <CXHAdSDK-Core/CXHAdSDK.h>

@interface CXHTradPlusSplashAdapter ()<CXHAdSDKSplashAdDelegate>

@property (nonatomic,strong) CXHAdSDKSplashAd *splashAd;

@property (nonatomic, assign) BOOL isInit;

@property (nonatomic, assign) BOOL isC2SBidding;

@end

@implementation CXHTradPlusSplashAdapter

//根据event实现相关流程
- (BOOL)extraActWithEvent:(NSString *)event info:(NSDictionary *)config
{
    if([event isEqualToString:@"C2SBidding"]){
        //从三方SDK获取价格
        [self getECPMC2SBidding];
    } else if([event isEqualToString:@"LoadAdC2SBidding"]) {
        //竞价成功后的加载流程
//        [self.splashAd sendWinNotice:self.splashAd.getBidPrice];
        [self loadAdC2SBidding];
    } else if ([event isEqualToString:@"C2SLoss"]) {
        NSString *topPirce = config[@"topPirce_cny"];
        [self.splashAd sendLossNotice:[topPirce integerValue]];
    } else {
        return NO;
    }
    return YES;
}

- (void)getECPMC2SBidding {
//    [self initSDK:self.waterfallItem.config];
    [self startC2SBidding];
}

- (void)loadAdC2SBidding {
    if ([self isReady]) {
        [self.splashAd sendWinNotice:self.splashAd.getBidPrice];
        [self AdLoadFinsh];
    }else{
        NSError *loadError = [NSError errorWithDomain:@"Load splash failed" code:-4 userInfo:@{NSLocalizedDescriptionKey : @"C2S splash not ready"}];
        [self AdLoadFailWithError:loadError];
    }
}

//通过三方API获取ECPM
- (void)startC2SBidding {
    self.isC2SBidding = YES;
    
    NSString *posid = self.waterfallItem.config[@"posid"];
    
    if (kCXHStringIsEmpty(posid)) {
        NSDictionary *dic = @{@"error": @"get bid price failed"};
//        [self ADLoadExtraCallbackWithEvent:@"C2SBiddingFail" info:dic];
        [self AdLoadFailWithError:[NSError errorWithDomain:@"get bid price failed" code:-1 userInfo:nil]];
        return;
    }
    
    self.splashAd.posId = posid;
    
    [self loadAdWithWaterfallItem:self.waterfallItem];
}

- (CXHAdSDKSplashAd *)splashAd{
    if (_splashAd == nil) {
        _splashAd = [[CXHAdSDKSplashAd alloc] init];
        _splashAd.delegate = self;
    }
    return _splashAd;
}

//初始化自定义平台，设置平台参数（海外平台的隐私设置）加载广告
- (void)loadAdWithWaterfallItem:(TradPlusAdWaterfallItem *)item{
    [self initSDK:self.waterfallItem.config];
    //通过 item.config 获取后台配置信息
    NSString *posid = item.config[@"posid"];
    
    if (kCXHStringIsEmpty(posid)) {
        [self AdConfigError];
        return;
    }
    
    self.splashAd.posId = posid;
    self.splashAd.setSkipButtonToRightTop = YES;
    NSInteger showTime = 5;
    NSDictionary *localParams = [item.extraInfoDictionary CXH_objectOrNilForKey:@"localParams"];
    if (localParams) {
        id rightSkip = [localParams CXH_objectOrNilForKey:@"rightskip"];
        if (rightSkip != nil && [rightSkip isEqualToString:@"false"]) {
            self.splashAd.setSkipButtonToRightTop = NO;
        }
        
        id time = [localParams CXH_objectOrNilForKey:@"showtime"];
        if (time != nil) {
            showTime = [time integerValue];
        }
    }
    self.splashAd.showTime = showTime;
    
    [self.splashAd loadSplashAd];
}

- (void)initSDK:(NSDictionary *)config {
    if (self.isInit) {
        return;
    }
    self.isInit = YES;
    NSString *domain = [config CXH_objectOrNilForKey:@"domain"];
    if (kCXHStringIsEmpty(domain)) {
        domain = @"";
    }
    NSString *appid = [config CXH_objectOrNilForKey:@"appid"];
    if (!kCXHStringIsEmpty(appid)) {
        [CXHAdSDK initWithAppId:appid requestDomain:domain completionBlock:^(NSError * _Nullable error) {
            if (error) {
                [self AdConfigError];
            }
        }];
    }
}

//此方法用于返回是否过期状态
- (BOOL)isReady
{
    return (self.splashAd != nil);
}

//展示广告
- (void)showAdInWindow:(UIWindow *)window bottomView:(UIView *)bottomView{
    if (!self.rootViewController) {
        self.splashAd.controller = window.rootViewController;
    }
    if (bottomView) {
//        self.splashAd.bottomView = bottomView;
        [self.splashAd showSplashInWindow:window bottomView:bottomView];
        return;
    }
    [self.splashAd showSplashAdInWindow:window];
}

#pragma mark - CXHAdSDKSplashAdDelegate
/**
 开屏广告点击回调, 可能会打开 AppStore, WebView, ThirdApp etc.

 @param splashAd 开屏广告
 @param loadingPageURL 广告落地页地址，当渠道为bwt，并且customLoadingPage为YES时有值
 */
- (void)CXH_splashAdDidClick:(CXHAdSDKSplashAd *)splashAd loadingPageURL:(NSString *)loadingPageURL{
    [self AdClick];
}

/**
 开屏广告关闭回调, 触发条件: 点击广告, 点击跳过, 超时关闭

 @param splashAd 开屏对象
 */
- (void)CXH_splashAdDidClose:(CXHAdSDKSplashAd *)splashAd{
    [self AdClose];
    _splashAd = nil;
}

/**
 开屏广告展示回调

 @param splashAd 开屏对象
 */
- (void)CXH_splashAdExposured:(CXHAdSDKSplashAd *)splashAd{
    [self AdShow];
}

/**
 开屏广告加载成功
 
 @param splashAd 开屏对象
 */
- (void)CXH_splashAdDidLoad:(CXHAdSDKSplashAd *)splashAd{
    if (self.isC2SBidding) {
        NSInteger price = self.splashAd.getBidPrice;
        if (price <= 0) {
            NSDictionary *dic = @{@"error": @"get bid price failed"};
            [self ADLoadExtraCallbackWithEvent:@"C2SBiddingFail" info:dic];
            return;
        }
        //通过接口向TradPlusSDK回传ecpm和三方版本号
        float f = price/100.00;
        NSString *ecpmStr = [NSString stringWithFormat:@"%.2f", f];
        NSDictionary *dic = @{@"ecpm":ecpmStr,@"version":[CXHAdSDK getSDKVersion]};
        [self ADLoadExtraCallbackWithEvent:@"C2SBiddingFinish" info:dic];
    } else {
        [self AdLoadFinsh];
    }
}

/**
 开屏广告加载失败
 
 @param splashAd 开屏对象
 */
- (void)CXH_splashAdDidFailToLoad:(CXHAdSDKSplashAd *)splashAd error:(NSError *)error{
    if(self.isC2SBidding)
    {
        NSDictionary *dic = @{@"error": @"c2s bidding load failed"};
        [self ADLoadExtraCallbackWithEvent:@"C2SBiddingFail" info:dic];
    }
    else
    {
        [self AdLoadFailWithError:error];
    }
}

/**
 *  开屏广告成功展示
 *
 *  @param splashAd 开屏对象
 */
- (void)CXH_splashAdSuccessPresentScreen:(CXHAdSDKSplashAd *)splashAd{
    
}

/**
 *  开屏广告展示失败
 *
 *  @param splashAd 开屏对象
 */
- (void)CXH_splashAdFailToPresent:(CXHAdSDKSplashAd *)splashAd withError:(NSError *)error{
    [self AdShowFailWithError:error];
}

/**
 *  开屏广告关闭落地页
 *
 *  @param splashAd 开屏对象
 */
- (void)CXH_splashAdCloseLandingPage:(CXHAdSDKSplashAd *)splashAd{
    
}

@end
